#include "util.hpp"
#include <stdio.h>
#include <vector>
#include <functional>

using func_t = std::function<void()>;

#define INIT(v)                 \
    do                          \
    {                           \
        v.push_back(printfLog); \
        v.push_back(download);  \
        v.push_back(executSql); \
    } while (0)

#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (const auto &cb : cbs) \
            cb();                  \
    } while (0)

int main()
{
    std::vector<func_t> cbs;
    INIT(cbs);

    setNonBlock(0);
    char buffer[1024];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
        }
        else
        {
            // 1.当我不输入的时候，底层没有数据，算错误吗？不算错误，只不过以错误的形式返回了
            // 2.我又如何区分，真的错了，还是底层没有数据？单纯的返回值，无法区分！
            std::cout << "result: " << s << "errno:" << strerror(errno) << std::endl;
            // std::cout << "EAGAIN: " << EAGAIN << " EWOUDLBLOCK: " << EWOULDBLOCK << std::endl;

            if (errno == EAGAIN)
            {
                std::cout << "我没错,只是没有数据" << std::endl;
            }
            if (errno == EINTR) // 也没错，只是收到信号被中断了，还有数据可能没读完，所以继续读
            {
                continue;
            }
            else
            {
                std::cout << "result: " << s << "errno:" << strerror(errno) << std::endl;
            }
        }

        EXEC_OTHER(cbs);
        sleep(1);
    }
}